#include <iostream>
#include <string>

using namespace std;

// 希望每个对象都有独立的拷贝，深拷贝

class HasPtr
{
public:
    HasPtr(const string &s = string()) : ps(new string(s)), i(0) {}
    HasPtr(const HasPtr &hp) : ps(new string(*hp.ps)), i(hp.i) {}

    HasPtr &operator=(const HasPtr &);
    HasPtr &operator=(const string &);
    string &operator*() const;
    ~HasPtr();

private:
    string *ps;
    int i;
};

HasPtr::~HasPtr()
{
    cout << "~HasPtr(): " << *ps << endl;
    delete ps;
    ps = nullptr;
}

inline HasPtr &HasPtr::operator=(const HasPtr &rhs)
{
    auto newp = new string(*rhs.ps);
    delete ps;
    ps = newp;
    i = rhs.i;
    return *this;
}

inline HasPtr &HasPtr::operator=(const string &rhs)
{
    *ps = rhs;
    return *this;
}

string &HasPtr::operator*() const
{
    return *ps;
}

int main()
{
    HasPtr hp("hi mom!");
    HasPtr hp2(hp);
    HasPtr hp3 = hp;
    hp2 = "hi dad!";
    hp3 = "hi grandma!";
    cout << "hp:\t" << *hp << endl;
    cout << "hp2:\t" << *hp2 << endl;
    cout << "hp3:\t" << *hp3 << endl;
}
